package order;

import controller.SessionAttribute;
import entity.AddressLocal;
import entity.AddressLocalHome;
import entity.CommentsLocalHome;
import entity.OrdersLocal;
import entity.OrdersLocalHome;
import entity.UsersLocal;
import entity.UsersLocalHome;
import entity.WarehouseLocal;
import entity.WarehouseLocalHome;
import helper.SimpleJSONObject;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import javax.ejb.CreateException;
import javax.ejb.FinderException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import transfer.Address;
import transfer.Comment;
import transfer.OrderState;
import transfer.User;
import transfer.Warehouse;

/**
 *
 * @author Oleh
 */
public class Order extends HttpServlet {

    public static final String emailParameter = "email";
    public static final String countryParameter = "country";
    public static final String cityParameter = "city";
    public static final String streetParameter = "street";
    public static final String homeParameter = "home";
    public static final String longitudeParameter = "longitude";
    public static final String latitudeParameter = "latitude";
    public static final String apartmentParameter = "apartment";
    public static final String subscribedParameter = "subscribed";
    public static final String warehouseParameter = "warehouse";
    public static final String distanceParameter = "distance";
    public static final String commentParameter = "comment";
    public static final String isNewAddressParameter = "isNewAddress";
    public static final String link = "link";

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            HttpSession session = request.getSession();
            User user = (User) session.getAttribute(SessionAttribute.USER);
            transfer.Order cart = (transfer.Order) session.getAttribute(SessionAttribute.CART);

            String email = request.getParameter(emailParameter);
            String county = request.getParameter(countryParameter);
            String city = request.getParameter(cityParameter);
            String street = request.getParameter(streetParameter);
            String home = request.getParameter(homeParameter);
            String apartment = request.getParameter(apartmentParameter);
            Double longitude = Double.valueOf(request.getParameter(longitudeParameter));
            Double latitude = Double.valueOf(request.getParameter(latitudeParameter));
            Boolean subscribed = Boolean.valueOf(request.getParameter(subscribedParameter));
            Integer warehouseId = Integer.valueOf(request.getParameter(warehouseParameter));
            Double distance = Double.valueOf(request.getParameter(distanceParameter));
            String comment = request.getParameter(commentParameter);
            Boolean isNewAddress = Boolean.valueOf(request.getParameter(isNewAddressParameter));

            System.out.println("subscribedString = " + request.getParameter(subscribedParameter));
            System.out.println("email = " + email);
            System.out.println("country = " + county);
            System.out.println("city = " + city);
            System.out.println("street = " + street);
            System.out.println("home = " + home);
            System.out.println("apartment = " + apartment);
            System.out.println("longitude = " + longitude);
            System.out.println("latitude = " + latitude);
            System.out.println("subscribed = " + subscribed);
            System.out.println("warehouse = " + warehouseId);
            System.out.println("distance = " + distance);
            System.out.println("comment = " + comment);
            System.out.println("isNewAddress = " + isNewAddress);

            Date creationDate = new Date();
            InitialContext context = new InitialContext();
            cart.setIsSubscribed(subscribed);
            WarehouseLocalHome warehouseHome = (WarehouseLocalHome) context.lookup("java:comp/env/Warehouse");
            WarehouseLocal warehouseLocal = (WarehouseLocal) warehouseHome.findByPrimaryKey(warehouseId);
            Warehouse warehouse = warehouseLocal.getWarehouse();
            cart.setWarehouse(warehouse);
            cart.setDistance(distance);
            cart.setCreationDate(creationDate);
            cart.setCostDelivery(new Double(distance.doubleValue() * warehouse.getShipmentRate().doubleValue()));
            cart.setTotalCost(new Double(cart.getCostCommodities().doubleValue() + cart.getCostDelivery().doubleValue()));
            cart.setOrderState(OrderState.QUEUED);

            if (user != null && !isNewAddress.booleanValue()) {
                cart.setAddress(user.getAddress());
            } else {
                Address address = new Address();
                address.setCountry(county);
                address.setCity(city);
                address.setStreet(street);
                address.setBuilding(home);
                address.setFlat(apartment);
                address.setLongitude(longitude);
                address.setLatitude(latitude);
                AddressLocalHome addressHome = (AddressLocalHome) context.lookup("java:comp/env/Address");
                AddressLocal addressLocal = addressHome.create(address);
                cart.setAddress(addressLocal.getAddress());
            }

            if (user == null && email != null && !email.equals("")) {
                cart.setEmail(email);
            }

            UsersLocalHome homeUser = (UsersLocalHome) context.lookup("java:comp/env/Users");
            UsersLocal localUser = (UsersLocal) homeUser.findNextWarehouseEmployee();
            User warehouseEmployee = localUser.getUser();
            cart.setWarehouseEmployee(warehouseEmployee);
            System.out.println("warehouse employee id = " + warehouseEmployee.getIdUser());

            OrdersLocalHome homeOrder = (OrdersLocalHome) context.lookup("java:comp/env/Orders");
            SimpleJSONObject json = new SimpleJSONObject();
            if (user != null) {
                OrdersLocal localOrder = (OrdersLocal) homeOrder.findByPrimaryKey(cart.getIdOrder());
                localOrder.setOrder(cart);
                saveComment(comment, cart, user, creationDate);
                cart = new transfer.Order();
                cart.setCustomer(user);
                cart.setOrderState(OrderState.ENTERING);
                cart.setTotalCost(new Double(0));
                cart.setIsSubscribed(Boolean.FALSE);
                cart.setCommodities(new HashMap());
                localOrder = homeOrder.create(cart);
                cart = localOrder.getOrder();
                session.setAttribute(SessionAttribute.CART, cart);
                json.addProperty(link, "index.jsp?content=dashboard");
            } else {
                OrdersLocal localOrder = (OrdersLocal) homeOrder.create(cart);
                cart = localOrder.getOrder();
                saveComment(comment, cart, user, creationDate);
                Integer idOrder = cart.getIdOrder();
                // new cart creates by order.Cart.java
                session.removeAttribute(SessionAttribute.CART);
                session.setAttribute(SessionAttribute.TRACKING_NUMBER, idOrder);
                json.addProperty(link, "index.jsp?content=endorder");
            }
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.println(json);

        } catch (NamingException ex) {
            ex.printStackTrace();
        } catch (FinderException ex) {
            ex.printStackTrace();
        } catch (CreateException ex) {
            ex.printStackTrace();
        }
    }

    private void saveComment(String comment, transfer.Order cart, User user, Date creationDate) {
        if (comment != null && !comment.equals("")) {
            try {
                Comment newComment = new Comment();
                if (user != null) {
                    newComment.setUser(user);
                }
                newComment.setOrder(cart);
                newComment.setOrderState(OrderState.QUEUED);
                newComment.setCommentText(comment);
                newComment.setCommentDate(creationDate);
                InitialContext context = new InitialContext();
                CommentsLocalHome commentsHome = (CommentsLocalHome) context.lookup("java:comp/env/Comments");
                commentsHome.create(newComment);
            } catch (NamingException ex) {
                ex.printStackTrace();
            } catch (CreateException ex) {
                ex.printStackTrace();
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
